package com.ygxsk.carhome.ui.property;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.RxFamilyMember;
import com.ygxsk.carhome.event.RxRightButton;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.HouseAuthBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.SelecetRoomAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023/12/28  15:20
 * @Description:报修选择房屋列表
 */
public class SelectRoomActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshLayoutinselect)
    SmartRefreshLayout refreshLayoutInSelect;

    @BindView(R.id.recyclerViewinselecroom)
    RecyclerView recyclerViewInSelecRoom;

    /**
     * 从哪里跳转过来的标识，跟rxbus刷新数据保持一致，物业报修、添加家庭成员、添加租客信息
     */
    private int flag_jumpFrom = 0;

    /**
     * 从添加报修界面跳转过来的已经选中的房屋id信息
     */
    private String houseIdPass = "";

    /**
     * 填充该列表数据
     */
    private ArrayList<HouseAuthBean> mDataResources = new ArrayList<>();

    /**
     * 该房间列表的适配器内容
     */
    private SelecetRoomAdapter selecetRoomAdapter;

    /**
     * 本界面监听右侧按钮内容
     */
    private final int RXBUS_RIGHTBUTTON = 14;

    /**
     * 顶部确认的监听内容
     */
//    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    /**
     * 顶部的标题的管理器
     */
    private ToolbarHelper toolbarHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        //在inittoolbar之后创建监听
        mCompositeDisposable.add(RxBus.getInstance().toObserverable(RxRightButton.class)
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxRightButton>() {
                    @Override
                    public void accept(RxRightButton rxRightButton) throws Throwable {

                        if (rxRightButton != null) {

                            if (rxRightButton.getMessage() == RXBUS_RIGHTBUTTON) {

                                if (toolbarHandler != null) {

                                    if (rxRightButton.isShowRightButton()) {

                                        toolbarHandler.setLayoutRight(true, 1, getString(R.string.button_sure_room), new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {

                                                //取出用户选择的房间信息。
                                                //关闭该界面。
                                                //信息传递到上一个界面。
                                                //没有数据列表时候隐藏掉。
                                                methodPost();

                                            }
                                        });
                                    } else {

                                        toolbarHandler.setLayoutRight(false, 1, "", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {

                                                //取出用户选择的房间信息。
                                                //关闭该界面。
                                                //信息传递到上一个界面。
                                                //没有数据列表时候隐藏掉。

                                            }
                                        });
                                    }
                                }

                            }

                        }


                    }
                }));

        gainDatas();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_select_room;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHandler = toolbarHelper;

        //选择房屋：
        toolbarHelper.setTitle(getResources().getString(R.string.title_select_room));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里是什么都没有的；
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(false, 1, "", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        recyclerViewInSelecRoom.setLayoutManager(new LinearLayoutManager(this));
        selecetRoomAdapter = new SelecetRoomAdapter(R.layout.selecetroomadapter, mDataResources);
        recyclerViewInSelecRoom.setAdapter(selecetRoomAdapter);

        selecetRoomAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "点击的位置是--->" + position);

                HouseAuthBean selectRoomBean = (HouseAuthBean) adapter.getItem(position);

                if (selectRoomBean != null) {

                    CheckBox checkBox = view.findViewById(R.id.imagepaymentselectinroom);//列表内的复选按钮

                    if (checkBox != null) {

//                        CommUtils.setButtonDrawable(checkBox);

                        int isChecked = selectRoomBean.getChecked();

                        if (isChecked == 0) {//如果当前状态是未被选中的状态
                            //互斥操作。列表是固定不变的可以一直用mDataResources
                            for (int index = 0; index < mDataResources.size(); index++) {//

                                if (index == position) {
                                    mDataResources.get(index).setChecked(1);
                                    checkBox.setChecked(true);
                                    //LogUtils.d("itchen---被选中的="+index+"---->"+mDataResources.get(index).getChecked());
                                } else {
                                    mDataResources.get(index).setChecked(0);
                                    checkBox.setChecked(false);
                                    //LogUtils.d("itchen---没有选中的="+index+"----------->"+mDataResources.get(index).getChecked());
                                }
                            }


                        } else if (isChecked == 1) {//如果当前状态是已经被选中的状态

                            //全部置空
                            for (int ind = 0; ind < mDataResources.size(); ind++) {
                                mDataResources.get(ind).setChecked(0);
                                checkBox.setChecked(false);
                            }

                        }

                        if (selecetRoomAdapter != null) {
                            selecetRoomAdapter.notifyDataSetChanged();
                        }

                        //==============================================================
                    }
                }

            }
        });


        //列表的刷新内容
        refreshLayoutInSelect.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                //这几种状态先放着。

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        gainDatas();

                        refreshLayout.finishRefresh();
                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (selecetRoomAdapter != null) {
            selecetRoomAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {

            //是否有其他的执行逻辑？
            netWorkError();
//            setEnableLoadmore(refreshLayoutConsignFragment, false);

        }


    }

    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();

        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.classify, FeePaymentWaterOrEleType.FEEPAYTYPE_ELE.getIndex());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERAUDITHOUSE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getFinanceGaugeByHouseList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerAuditHouse(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(FeeElectricFragment.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<HouseAuthBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

//                        CommUtils.checkMaterialDialog(materialDialog);
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);

                        loadingGone();

                    }
                }).subscribe(new Consumer<ArrayList<HouseAuthBean>>() {
                    @Override
                    public void accept(ArrayList<HouseAuthBean> houseAuthBeanArrayList) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

//                        if (feeElectricOutSideBean != null) {

                        //----------------------------------------------------------------------------------------------------
                        //2023-12-23 16:52:36 发现bug,没有清空的话，支付方式一直累加成多条
//                            if (feePayTypeListBeanArrayListDatas != null) {
//                                feePayTypeListBeanArrayListDatas.clear();
//                            }

                        //支付方式列表
//                            ArrayList<FeePayTypeListBean> feePayTypeListBeanArrayList = feeElectricOutSideBean.getPayTypeList();
//
//                            if (feePayTypeListBeanArrayList != null && !feePayTypeListBeanArrayList.isEmpty()) {
//
//                                if (feePayTypeListBeanArrayListDatas != null) {
//                                    feePayTypeListBeanArrayListDatas.addAll(feePayTypeListBeanArrayList);
//                                }
//
//                            }
                        //----------------------------------------------------------------------------------------------------
                        //水表待支付列表信息
//                            ArrayList<FeeLivingExpensesBean> feeLivingExpensesArrayList = feeElectricOutSideBean.getGaugeList();
//
//                            if (feeLivingExpensesArrayList != null && !feeLivingExpensesArrayList.isEmpty()) {
//
//                                if (mDataResources != null) {
//
//                                    mDataResources.addAll(feeLivingExpensesArrayList);
//
//                                    //绑定多少个水表
//                                    text_top_bindCount(mDataResources.size());
//
//                                }
//                            }
//                        }
                        //---------------------------------------------------------------------------------------------------

                        if (houseAuthBeanArrayList != null && !houseAuthBeanArrayList.isEmpty()) {

                            if (mDataResources != null) {
                                mDataResources.addAll(houseAuthBeanArrayList);
                            }

                        }


                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
//                            if (refreshLayoutInLeadsActivity != null) {
//                                refreshLayoutInLeadsActivity.setEnableLoadMore(false);
//                            }

                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

                        }

                        if (selecetRoomAdapter != null) {
                            selecetRoomAdapter.notifyDataSetChanged();
                        }

                        if (flag_jumpFrom == ExtraValue.RXBUS_PROPERTYREPAIRADD) {

                            if (!TextUtils.isEmpty(houseIdPass)) {

                                for (HouseAuthBean houseAuthBean : mDataResources) {
                                    //如果两个houseId相同那么设置为选中checked状态
                                    if (TextUtils.equals(houseIdPass, houseAuthBean.getHouseId())) {
                                        //LogUtils.d("itchen---物业报修界面上次选中的房屋id==>"+houseAuthBean.getHouseId());
                                        houseAuthBean.setChecked(1);
                                        break;
                                    }
                                }

                            }

                        }


                        //最后一步展示出来确定按钮。
                        RxRightButton rxRightButton = new RxRightButton();
                        rxRightButton.setMessage(RXBUS_RIGHTBUTTON);
                        rxRightButton.setShowRightButton(true);
                        RxBus.getInstance().post(rxRightButton);


                    }

                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETCUSTOMERAUDITHOUSE_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

//                    setEnableLoadmore(re, false);

                    CommUtils.checkCurrently(SelectRoomActivity.this,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));

                }

                break;
            }

            default:
                break;
        }
    }


    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    private void methodPost() {

        //判断是否选中房间内容

        //传递信息
//        if (flag_jumpFrom == ConstantApi.RXBUS_FAMILYMEMBERADD) {
//
//            RxFamilyMember rxFamilyMemberMember = new RxFamilyMember();
//
//            for (HouseAuthBean selectRoomBean : mDataResources) {
//
//                if (selectRoomBean.getChecked() == 1) {
//
//                    rxFamilyMemberMember.setMessage(ConstantApi.RXBUS_FAMILYMEMBERADD);
//                    rxFamilyMemberMember.setRoomBean(selectRoomBean);
//                    //LogUtils.d("itchen--member选中了--"+selectRoomBean.getHouseId());
//
//                    break;
//                }
//            }
//
//            if (rxFamilyMemberMember.getMessage() == -1) {
//
//                method_alertView("请选择房间");
//
//                return;
//
//            }
//
//
//            RxBus.getInstance().post(rxFamilyMemberMember);
//
//
//        } else

//        if (flag_jumpFrom == ConstantApi.RXBUS_FAMILYTENANTADD) {
//
//            RxFamilyMember rxFamilyMemberTenant = new RxFamilyMember();
//
//            for (HouseAuthBean selectRoomBean : mDataResources) {
//
//                if (selectRoomBean.getChecked() == 1) {
//                    rxFamilyMemberTenant.setMessage(ConstantApi.RXBUS_FAMILYTENANTADD);
//                    rxFamilyMemberTenant.setRoomBean(selectRoomBean);
//
//                    //LogUtils.d("itchen--tenant选中了--"+selectRoomBean.getHouseId());
//                    break;
//                }
//            }
//
//            if (rxFamilyMemberTenant.getMessage() == -1) {
//
//                method_alertView("请选择房间");
//
//                return;
//
//            }
//
//            RxBus.getInstance().post(rxFamilyMemberTenant);
//
//
//        } else


        if (flag_jumpFrom == ExtraValue.RXBUS_PROPERTYPAYMENT) {//如果是从物业缴费列表过来的

            //从其他待处理的界面跳转过来。 处理列表同上。
            RxFamilyMember rxFamilyMemberPayment = new RxFamilyMember();

            for (HouseAuthBean selectRoomBean : mDataResources) {

                if (selectRoomBean.getChecked() == 1) {
                    rxFamilyMemberPayment.setMessage(ExtraValue.RXBUS_PROPERTYPAYMENT);
                    rxFamilyMemberPayment.setRoomBean(selectRoomBean);
                    //LogUtils.d("itchen--tenant选中了--"+selectRoomBean.getHouseId());
                    break;
                }
            }

            if (rxFamilyMemberPayment.getMessage() == -1) {

//                method_alertView("请选择房间");

                CommUtils.checkDialog(mAlertView);
                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_room), true);
                mAlertView.show();

                return;

            }

            RxBus.getInstance().post(rxFamilyMemberPayment);


        } else if (flag_jumpFrom == ExtraValue.RXBUS_PROPERTYREPAIRADD) {//如果 是从添加报修过来的

            RxFamilyMember rxFamilyMemberRepairAdd = new RxFamilyMember();

            for (HouseAuthBean selectRoomBean : mDataResources) {

                if (selectRoomBean.getChecked() == 1) {

                    rxFamilyMemberRepairAdd.setMessage(ExtraValue.RXBUS_PROPERTYREPAIRADD);
                    rxFamilyMemberRepairAdd.setRoomBean(selectRoomBean);

                    LogUtils.d("itchen--tenant 添加报修过来的-选中了--" + selectRoomBean.getHouseId());

                    break;

                } else {
                    LogUtils.d("itchen--tenant 添加报修过来的-没有选中任何");
                }

            }

            if (rxFamilyMemberRepairAdd.getMessage() == -1) {

//                method_alertView("请选择房间");
                CommUtils.checkDialog(mAlertView);
                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_room), true);
                mAlertView.show();

                return;

            }

            RxBus.getInstance().post(rxFamilyMemberRepairAdd);

        }

//        else if (flag_jumpFrom == ConstantApi.VALUE_JUMPFROM_COMMODITYBORROW_ADDSUBMIT) {//如果是从【物品借用过来的】
//            methodRxBusMessage(ConstantApi.RXBUS_MODITYBORROW_ADDSUBMIT);
//        }

        methodBack();

    }

    @Override
    public void processExtraData() {

        Bundle bundle = getIntent().getExtras();
        //use the data received here

        if (bundle != null) {

            flag_jumpFrom = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);//从哪里跳转过来的标识

            if (flag_jumpFrom == ExtraValue.RXBUS_PROPERTYPAYMENT) {//如果是从物业缴费过来的

                houseIdPass = bundle.getString(ExtraKey.EXTRA_PROPERTYPAYMENTHOUSEIDPASS);

            } else if (flag_jumpFrom == ExtraValue.RXBUS_PROPERTYREPAIRADD) {//如果是从添加报修过来的

                houseIdPass = bundle.getString(ExtraKey.EXTRA_PROPERTYREPAIRADDHOUSEIDPASS);

            }

//            else if (flag_jumpFrom == ConstantApi.RXBUS_FAMILYMEMBERADD) {//如果是从添加家庭成员过来的
//
//                houseIdPass = bundle.getString(ExtraKey.EXTRA_FAMILYMEMBERADDHOUSEIDPASS);
//
//            }

//            else if (flag_jumpFrom == ConstantApi.RXBUS_FAMILYTENANTADD) {//如果是从添加租客跳转过来的
//
//                houseIdPass = bundle.getString(ExtraKey.EXTRA_FAMILYTENANTADDHOUSEIDPASS);
//            }

            //LogUtils.d("itchen---携带过来的houseIdPass="+houseIdPass);

        }


    }
}